package com.example.nfc.server.utils;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.example.nfc.R;
import com.example.nfc.dialog.AlertDialog;
import com.example.nfc.server.utils.json.JsonMananger;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * [公共工具类，与Android API相关的辅助类]
 *
 **/
public class CommonUtils {

    @SuppressWarnings("unused")
    private static final String tag = CommonUtils.class.getSimpleName();

    /** 网络类型 **/
    public static final int NETTYPE_WIFI = 0x01;
    public static final int NETTYPE_CMWAP = 0x02;
    public static final int NETTYPE_CMNET = 0x03;

    /**
     * 检测网络是否可用
     *
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if(context==null){
            return true;
        }
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnectedOrConnecting();
    }

    /**
     * 获取当前网络类型
     *
     * @return 0：没有网络 1：WIFI网络 2：WAP网络 3：NET网络
     */
    public static int getNetworkType(Context context) {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            String extraInfo = networkInfo.getExtraInfo();
            if (!TextUtils.isEmpty(extraInfo)) {
                if (extraInfo.toLowerCase(Locale.getDefault()).equals("cmnet")) {
                    netType = NETTYPE_CMNET;
                } else {
                    netType = NETTYPE_CMWAP;
                }
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = NETTYPE_WIFI;
        }
        return netType;
    }


    /**
     * 判断SDCard是否存在,并可写
     *
     * @return
     */
    public static boolean checkSDCard() {
        String flag = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(flag);
    }

    /**
     * 获取屏幕宽度
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    /**
     * 获取屏幕高度
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    /**
     * 获取屏幕显示信息对象
     * @param context
     * @return
     */
    public static DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm;
    }

    /**
     * dp转pixel
     */
    public static float dpToPixel(float dp, Context context) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        return dp * (metrics.densityDpi / 160f);
    }

    /**
     * pixel转dp
     */
    public static float pixelsToDp(float px, Context context) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        return px / (metrics.densityDpi / 160f);
    }
    /**
     * 短信分享
     *
     * @param mContext
     * @param smstext 短信分享内容
     * @return
     */
    public static Boolean sendSms(Context mContext, String smstext) {
        Uri smsToUri = Uri.parse("smsto:");
        Intent mIntent = new Intent(Intent.ACTION_SENDTO, smsToUri);
        mIntent.putExtra("sms_body", smstext);
        mContext.startActivity(mIntent);
        return null;
    }


    /**
     * 获取一个随机数
     * @return
     */
    public static String getRandomString() {
        Random random = new Random();
        String randomChar = String.valueOf(random.nextInt(100000000));
        return randomChar;
    }

    /**
     * 邮件分享
     *
     * @param mContext
     * @param title 邮件的标题
     * @param text 邮件的内容
     * @return
     */
    public static void sendMail(Context mContext, String title, String text) {
        // 调用系统发邮件
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
        // 设置文本格式
        emailIntent.setType("text/plain");
        // 设置对方邮件地址
        emailIntent.putExtra(Intent.EXTRA_EMAIL, "");
        // 设置标题内容
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, title);
        // 设置邮件文本内容
        emailIntent.putExtra(Intent.EXTRA_TEXT, text);
        mContext.startActivity(Intent.createChooser(emailIntent, "Choose Email Client"));
    }

    /**
     * 隐藏软键盘
     * @param view
     */
    public static void hideKeyboard(View view) {
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm.isActive()) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }

    /**
     * 显示软键盘
     * @param view
     */
    public static void showKeyboard(View view) {
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (!imm.isActive()) {
                view.requestFocus();
                imm.showSoftInput(view, 0);
            }
        }
    }

    /**
     * 是否横屏
     * @param context
     * @return true为横屏，false为竖屏
     */
    public static boolean isLandscape(Context context) {
        return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
    }

    /**
     * 判断是否是平板
     * 这个方法是从 Google I/O MyApp for Android 的源码里找来的，非常准确。
     * @param context
     * @return
     */
    public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 处理Intent的参数
     * @param obj
     * @return
     */
    public static Intent getIntent(Object...obj){
        Intent intent = new Intent();
        if(obj.length>0){
            for(int i = 0 ; i < obj.length;i++){
                if(obj[i] instanceof String){
                    intent.putExtra("ext_"+i,(String)obj[i]);
                }else if(obj[i] instanceof Integer){
                    intent.putExtra("ext_"+i,(int)obj[i]);
                }else if(obj[i] instanceof Float){
                    intent.putExtra("ext_"+i,(float)obj[i]);
                }else if(obj[i] instanceof com.example.nfc.server.bean.IntentKV){
                    com.example.nfc.server.bean.IntentKV intentKV = (com.example.nfc.server.bean.IntentKV)obj[i];
                    if(intentKV.getFlag()!=null){
                        intent.addFlags(intentKV.getFlag());
                    }
                    if(intentKV.getValue()!=null) {
                        if (intentKV.getValue() instanceof String) {
                            intent.putExtra(intentKV.getKey(), (String) intentKV.getValue());
                        } else if (intentKV.getValue() instanceof Integer) {
                            intent.putExtra(intentKV.getKey(), (int) intentKV.getValue());
                        } else if (intentKV.getValue() instanceof Float) {
                            intent.putExtra(intentKV.getKey(), (float) intentKV.getValue());
                        } else {
                            String json = null;
                            try {
                                json = JsonMananger.beanToJson(intentKV.getValue());
                            } catch (Exception e) {
                                Log.e("getIntent", e.getMessage());
                            }
                            intent.putExtra(intentKV.getKey(), json);
                        }
                    }
                }
            }
        }
        return intent;
    }

    /**
     * 获取字符之间的内容
     * left为特殊字符时 需加 \\
     * @param str
     * @param left
     * @param right
     * @return
     */
    public static List<String> getBetwendStr(String str, String left, String right){
        String regex = left+"(.*?)"+right;
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        List<String> s = new ArrayList<>();
        while (matcher.find()) {
            s.add(matcher.group(1));
        }
        return s;
    }

    /**
     * 判断某list 是否存在某字符
     * @param list
     * @param str
     * @return
     */
    public static boolean hasStr(List<String> list, String str){
        if(list.size()==0){
            return false;
        }
        for(String s:list){
            if(s.contains(str)){
                return true;
            }
        }
        return false;
    }

    public static String getMetaData(Context mContext, String key){
        try {
            ApplicationInfo appInfo = mContext.getPackageManager().getApplicationInfo(mContext.getPackageName(), PackageManager.GET_META_DATA);
            return  appInfo.metaData.getString(key);
        }catch (Exception e){
            NLog.e("getMetaData->"+key,e.getMessage());
        }
        return null;
    }
    /**
     *  选择框处理
     * @param mContext
     * @param mRg
     * @param radioButton
     * @param position
     */
    public static void setRadioButtonDrawable(Context mContext, RadioGroup mRg, RadioButton radioButton, int position){
        for(int i = 0 ;i<mRg.getChildCount();i++){
            if(position!=i) {
                Drawable drawable = mContext.getResources().getDrawable(R.mipmap.icon_blank);
                drawable.setBounds(0, 0, drawable.getMinimumWidth()*2/3, drawable.getMinimumHeight()*2/3);
                RadioButton tRadio = ((RadioButton)mRg.getChildAt(i));
                tRadio.setCompoundDrawables(drawable, null, null, null);
                tRadio.setTextColor(mContext.getResources().getColor(R.color.orderStatusText));
            }
        }
        Drawable drawable= mContext.getResources().getDrawable(R.mipmap.icon_select);
        drawable.setBounds(0, 0, drawable.getMinimumWidth()*2/3, drawable.getMinimumHeight()*2/3);
        radioButton.setCompoundDrawables(drawable,null,null,null);
        radioButton.setTextColor(mContext.getResources().getColor(R.color.orderStatusTextPress));
    }
    public static void checkABICanSupport(final Activity activity, final String title, final CheckAPICanSupportBack c){
        String CUP_ABI = Build.CPU_ABI;
        if("armeabi".equals(CUP_ABI)||"armeabi-v7a".equals(CUP_ABI)||"arm64-v8a".equals(CUP_ABI)){
            c.support();
        }else{
            AlertDialog alertDialog = new AlertDialog(activity);
            alertDialog.setTitle("系统提示");
            alertDialog.setContent("很抱歉,格力易派"+title+"所依赖的底层技术只支持ARM系列处理器的设备,暂不支持您的设备！");
            alertDialog.setSubmitTxt("确定");
            alertDialog.setCancelTxt("关闭");
            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
                    c.notSupport();
                }
            });
            alertDialog.show();
        }
    }
    public interface CheckAPICanSupportBack{
        void support();
        void notSupport();
    }

}
